/*
 * Created on 2005-5-16
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.haoxi.gateway.connector.impl;

import java.io.IOException;
import java.net.Socket;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.GatewayInfo;
import com.haoxi.gateway.connector.Connector;
import com.haoxi.gateway.runner.QueueMgr;
import com.haoxi.gateway.runner.ReciverDeliverThread;
import com.haoxi.gateway.runner.RunnerMgr;

/**
 * @author Administrator Window - Preferences - Java - Code Style - Code
 *         Templates
 */
public class SGIPPooledConnHandler implements Runnable {
    private boolean running = false;
    private static int count = 0;
    private static final Log log = LogFactory
            .getLog(SGIPPooledConnHandler.class);

    private static List pool = new LinkedList();

    private static List oldPool = new LinkedList();
    private Connector connector;

    public SGIPPooledConnHandler(Connector connector) {
        this.connector = connector;
    }

    public static void addConnectorIntoPool(String conname) {
        synchronized (oldPool) {
            oldPool.add(conname);
        }
    }

    // 往处理池，添加一个需要处理的请求
    public void processRequest(Socket requestToHandle) {
        synchronized (pool) {
            pool.add(pool.size(), requestToHandle);
            pool.notifyAll();
        }
    }

    /**
     * 具体的处理
     * 
     * @param socketConn 请求
     */
    public void process(Socket socketConn) {
        if (null == socketConn) {
            return;
        }
        Connector connector = null;
        log.debug("PooledConnHandler.process() start deal Socket:"
                        + socketConn);
        GatewayInfo gatewayInfo = RunnerMgr.getInstance().getGatewayInfo();

        if (oldPool.size() > 0) {
            synchronized (oldPool) {
                connector = (Connector) gatewayInfo.getCanReciveDeliverConns().get(oldPool
                        .remove(0));
            }
            connector.setSocInfo(socketConn);
        } else {
            connector = createNewConnector();
            connector.setSocInfo(socketConn);
            gatewayInfo.addCanReciveDeliverConn(connector.getConnName(), connector);
            new Thread(new ReciverDeliverThread(connector, QueueMgr
                    .getInstance().getReciveQueue())).start();
        }
        log.debug("PooledConnHandler.process() deal Socket successfully!");

    }

    /**
     * 创建一个新的连接器
     * @return
     */
    private Connector createNewConnector() {
        String connName = connector.getConnName() + (++count);
        GatewayInfo gatewayInfo = RunnerMgr.getInstance().getGatewayInfo();
        return new SGIPDeliverConnector(gatewayInfo.getGatewayCode(), connName,
                gatewayInfo.getIcp_id(), connector.getLoginName(),
                connector.getPassword(), null, connector.getGatewayPort(),
                connector.getVersion(), gatewayInfo.getProtocolName());
    }

    /**
     * 运行
     */
    public void run() {
        Object obj = null;
        log.debug("Runable: SGIPPooledConnHandler start !!!");
        running = true;
        try {
            while (running) {
                synchronized (pool) {
                    if (pool.isEmpty()) {
                        try {
                            // server所有的线程都等待
                            pool.wait();

                        } catch (InterruptedException e) {
                            continue;
                        }
                    }
                    // 在池不空的时候进行处理
                    else {
                        obj = pool.remove(0);
                        if (obj instanceof Socket) {
                            try {
                                process((Socket) obj);
                            } catch (Exception e) {
                                log.error("process error:", e);
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            log.error("SGIPPooledConnHandler socket pool process error !!!", e);
        } finally {
            if (pool.size() > 0) {
                Iterator ite = pool.iterator();
                if (ite.hasNext()) {
                    Socket socket = (Socket) ite.next();
                    if (null != socket) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        }
        running = false;
        log.debug("Runable: SGIPPooledConnHandler end !!!");
    }

}